package zisu.netty.practice.netty.protocoltcp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import org.omg.PortableInterceptor.INACTIVE;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * @Desc: ""
 * @Author: caixiang
 * @DATE: 2020/8/4 9:49
 */
//处理业务
public class MyServerHandler extends SimpleChannelInboundHandler<MessageProtocol> {
    private int count;
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
        //接收到数据并处理
        int len = msg.getLen();
        byte[] content = msg.getContent();
        System.out.println("服务端接受到信息如下：1.长度"+len+",content:"+new String(content, StandardCharsets.UTF_8));
        System.out.println("服务器接收到消息包 数量："+ (++count));

        //回复消息
        String responseContent = UUID.randomUUID().toString();
        int lens = responseContent.getBytes(CharsetUtil.UTF_8).length;
        //构建一个协议包
        MessageProtocol messageProtocol = new MessageProtocol();
        messageProtocol.setLen(lens);
        messageProtocol.setContent(responseContent.getBytes(CharsetUtil.UTF_8));
        ctx.writeAndFlush(messageProtocol);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
